package service;

import java.util.HashMap;
import java.util.List;

import model.PtManage;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import dao.PtManageDao;

;

@Service
public class PtManageService {
	@Autowired
	private PtManageDao ptManageDao;

	/**
	 * 单位管理列表的树形结构
	 * 
	 * @param id
	 * @return
	 */
	public List<HashMap<String, Object>> queryTree(Integer id) {
		return ptManageDao.queryTree(id);
	}

	/**
	 * 根据父节点获取完整的树形结构
	 * 
	 * @param pid
	 * @return
	 */
	public List<PtManage> getTreeBypid(Integer pid) {
		List<PtManage> list = ptManageDao.queryTreeList(pid);
		if (list.size() > 0) {
			for (int i = 0; i < list.size(); i++) {
				list.get(i).setChildren(getTreeBypid(list.get(i).getId()));
			}
		}
		return list;
	}

	public List<PtManage> getByPid(Integer pid) {
		return ptManageDao.queryTreeList(pid);
	}

	/**
	 * 保存单位信息
	 * 
	 * @param department
	 */
	public void saveOrUpdate(PtManage department) {
		if (department.getPid() == null || department.getPid() == 0) {
			department.setPid(0);
			department.setLevel(1);
		} else {
			PtManage pdepartment = ptManageDao.getById(department.getPid());
			Integer plevel = pdepartment.getLevel();
			department.setLevel(plevel + 1);
			if ("true".equals(pdepartment.getLeaf())) {
				pdepartment.setLeaf("false");
				ptManageDao.update(pdepartment);
			}
		}
		if (department.getId() == null) {
			ptManageDao.save(department);
		} else {
			ptManageDao.update(department);
		}
	}

}
